<?php

namespace app\admin\controller\coursetable;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 
 *
 * @icon fa fa-file
 */
class Classroomeplan extends Backend
{

    /**
     * Classroomeplan模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists", "status", "index", "edit", "getTimeSlotOccupancy","checkRecord"];
    protected $noNeedLogin = ["lists", "status", "index", "edit", "getTimeSlotOccupancy","checkRecord"];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid = false;
        $this->model = model('Classroomeplan');
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->alias("classroomeplan")
                ->join("eb_classes classes", "classroomeplan.classes_id=classes.id", "LEFT")
                ->join("fa_course_table coursetable", "classroomeplan.table_id=coursetable.id", "LEFT")
                ->join("fa_ocation ocation", "classroomeplan.ocation_id=ocation.id", "LEFT")
                ->field("classroomeplan.*,classes.name as classes_name,coursetable.name as table_name,ocation.name as ocation_name");
            if (isset($_REQUEST["search"]) && $_REQUEST["search"] != "") {
                $total = $total->where("classes.name", "like", $_REQUEST["search"]);
            }
            $total = $total->where("classroomeplan.status", "<>", -1);
            $total = $total
                ->count();

            $list = $this->model->alias("classroomeplan")
                ->join("eb_classes classes", "classroomeplan.classes_id=classes.id", "LEFT")
                ->join("fa_course_table coursetable", "classroomeplan.table_id=coursetable.id", "LEFT")
                ->join("fa_ocation ocation", "classroomeplan.ocation_id=ocation.id", "LEFT")
                ->field("classroomeplan.*,classes.name as classes_name,coursetable.name as table_name,ocation.name as ocation_name");
            if (isset($_REQUEST["search"]) && $_REQUEST["search"] != "") {
                $list = $list->where("classes.name", "like", $_REQUEST["search"]);
            }
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}纬武社区教学点党群服务中心 2025级银龄春季养生保健基础3班
            $list = $list->where("classroomeplan.status", "<>", -1)
                ->order('classroomeplan.weigh desc,classroomeplan.id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 调试：记录SQL和结果
            // \think\Log::write('Classroomeplan SQL: ' . $this->model->getLastSql(), 'debug');
            $list = collection($list)->toArray();
            for ($i = 0; $i < count($list); $i++) {
                $list[$i]['classes_id'] = model("Classes")->getClasses_idTextAttr($list[$i]['classes_id'], $list[$i]);
                $list[$i]['table_id'] = model("Coursetable")->getCoursetable_idTextAttr($list[$i]['table_id'], $list[$i]);
                $list[$i]['ocation_id'] = model("Ocation")->getOcation_idTextAttr($list[$i]['ocation_id'], $list[$i]);

                // 处理周几字段 - 支持多种格式
                if (isset($list[$i]['week']) && $list[$i]['week'] !== '' && $list[$i]['week'] !== null) {
                    $weekMap = ['1' => '周一', '2' => '周二', '3' => '周三', '4' => '周四', '5' => '周五', '6' => '周六', '7' => '周日'];
                    // 如果已经是中文，直接显示
                    if (strpos($list[$i]['week'], '周') !== false) {
                        // 已经是中文格式，不处理
                    } else {
                        // 数字格式，需要转换
                        $weeks = explode(',', $list[$i]['week']);
                        $weekNames = [];
                        foreach ($weeks as $w) {
                            $w = trim($w);
                            if (isset($weekMap[$w])) {
                                $weekNames[] = $weekMap[$w];
                            }
                        }
                        if (!empty($weekNames)) {
                            $list[$i]['week'] = join(',', $weekNames);
                        }
                    }
                }

                // 处理时段字段 - 支持多种格式（可能是时间段如"08:30-10:00"或数字）
                if (isset($list[$i]['daytime']) && $list[$i]['daytime'] !== '' && $list[$i]['daytime'] !== null) {
                    // 如果包含冒号，说明是时间格式，直接显示
                    if (strpos($list[$i]['daytime'], ':') !== false) {
                        // 已经是时间格式，不处理
                    } else {
                        // 数字格式，需要转换
                        $daytimeMap = ['1' => '上午', '2' => '中午', '3' => '下午', '4' => '晚上'];
                        $daytimes = explode(',', $list[$i]['daytime']);
                        $daytimeNames = [];
                        foreach ($daytimes as $d) {
                            $d = trim($d);
                            if (isset($daytimeMap[$d])) {
                                $daytimeNames[] = $daytimeMap[$d];
                            }
                        }
                        if (!empty($daytimeNames)) {
                            $list[$i]['daytime'] = join(',', $daytimeNames);
                        }
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        //        $this->assignconfig("relType",$_REQUEST['relType']);
        //        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $schedules = $this->request->post("schedules/a");

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    if ($params['classes_id'] < 0 || preg_match("/_/", $params['classes_id'])) {
                        $this->error("请选择班级");
                    }

                    // 处理多时间段数据 - 每个时间段单独存储
                    $timeSchedules = [];
                    if (isset($schedules) && is_array($schedules)) {
                        // 验证时间段数据并准备单独的记录
                        foreach ($schedules as $schedule) {
                            if (
                                !isset($schedule['week']) || !isset($schedule['daytime']) ||
                                trim($schedule['week']) == "" || trim($schedule['daytime']) == ""
                            ) {
                                $this->error("请完整填写所有时间段");
                            }

                            $timeSchedules[] = [
                                'week' => trim($schedule['week']),
                                'daytime' => trim($schedule['daytime'])
                            ];
                        }
                    } else {
                        // 兼容原有的单时间段处理
                        if (!isset($params['daytime']) || trim($params['daytime']) == "") {
                            $this->error("请选择时段");
                        }

                        $timeSchedules[] = [
                            'week' => $params['week'],
                            'daytime' => $params['daytime']
                        ];
                    }

                    if (empty($timeSchedules)) {
                        $this->error("请至少添加一个时间段");
                    }

                    //验证是否使用对了教室的类型
                    $r = model("Ocation")->where("id", "in", $params["ocation_id"])->select();
                    $r2 = model("Classplant")->where("classes_id", "in", $params["classes_id"])->where("status", 1)->select();
                    if (isset($r)) {
                        $ocation_type = $r[0]["ocation_type"];
                        if (!in_array($ocation_type, explode(",", $r2[0]["ocation_type"]))) {
                            $this->error("该教室类型与所选教室类型不一致");
                        }
                    }

                    // 检查每个时间段的冲突
                    foreach ($timeSchedules as $schedule) {
                        $week = $schedule['week'];
                        $daytime = $schedule['daytime'];

                        // 检查该教室在该时间段是否已被占用
                        $conflictCheck = $this->checkTimeConflict($params["ocation_id"], $week, $daytime);

                        if (!empty($conflictCheck)) {
                            $weekMap = ['1' => '周一', '2' => '周二', '3' => '周三', '4' => '周四', '5' => '周五', '6' => '周六', '7' => '周日'];
                            $weekText = isset($weekMap[$week]) ? $weekMap[$week] : $week;

                            // 获取冲突的班级和课程信息
                            $conflictClass = model("Classes")->where("id", "=", $conflictCheck[0]['classes_id'])->find();
                            $conflictClassName = $conflictClass ? $conflictClass['name'] : '未知班级';

                            $conflictCourse = model("Coursetable")->where("id", "=", $conflictCheck[0]['table_id'])->find();
                            $conflictCourseName = $conflictCourse ? $conflictCourse['name'] : '未知课程';

                            $this->error("教室在{$weekText} {$daytime}时段已被【{$conflictClassName}】的【{$conflictCourseName}】课程占用，请选择其他时间段或教室");
                        }
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }

                    // 为每个时间段创建单独的记录
                    $datatime = date("Y-m-d H:i:s");
                    $successCount = 0;

                    // 构建查询对象并打印SQL
                    $coursetableQuery = model("Coursetable")
                        ->where("classes_id", "like", "%," . $params["classes_id"] . ",%")
                        ->whereOr("classes_id", "like", "%," . $params["classes_id"])
                        ->whereOr("classes_id", "like", $params["classes_id"] . ",%")
                        ->whereOr("classes_id", "=", $params["classes_id"]);

                    // 打印SQL用于调试
//                    $sql = $coursetableQuery->buildSql();
//                    error_log("=== 查找课程表ID的SQL ===");
//                    error_log("参数: classes_id=" . $params["classes_id"]);
//                    error_log("SQL: " . $sql);

                    // 执行查询并安全获取结果
                    $coursetableResult = $coursetableQuery->find();
                    if (empty($coursetableResult)) {
                        $this->error("未找到对应的课程表记录，classes_id: " . $params["classes_id"]);
                    }
                    $table_id = $coursetableResult["id"];
                    foreach ($timeSchedules as $schedule) {
                        $recordData['classes_id'] = $params["classes_id"];
                        $recordData['ocation_id'] = $params["ocation_id"];
                        $recordData['table_id'] = $table_id;
                        $recordData['ocourse_count'] = $params["ocourse_count"]??17;
                        $recordData['classes_per_week'] = $params["classes_per_week"]??1;
                        $recordData['week'] = $schedule['week'];
                        $recordData['daytime'] = $schedule['daytime'];
                        $recordData['create_time'] = $datatime;
                        $recordData['update_time'] = $datatime;
                        $recordData['status'] = 1;
                        unset($recordData['delete_time']);
                        unset($recordData['ocourse_count']);
                        unset($recordData['classes_per_week']);
                        unset($recordData['id']);
                        $result = $this->model->insertUpdate($recordData, ["ocation_id", "classes_id", "week", "daytime"]);
                        if ($result) {
                            $successCount++;
                        }
                    }

                    if ($successCount > 0) {
                        $this->success("成功创建了 {$successCount} 条时间段记录");
                    } else {
                        $this->error("创建记录失败");
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $_REQUEST['classesName'] = preg_replace("/\(.*$/", "", $_REQUEST['classesName']);
        $classes = model("Classes")->where("name", "like", "%" . $_REQUEST['classesName'] . "%")->where("status", 1)->find();
        $this->assignconfig("classesName", urldecode($_REQUEST['classesName']));
        $this->assign("classesId", $classes["id"]);
        $this->assignconfig("subject_lv", $classes["subject_lv"]);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        return $this->view->fetch('add');
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        if(!empty($this->request->param('planids'))){
            $classes_id=$this->request->param('planids');
        }else if(!empty($this->request->param('classes_id'))){
            $classes_id=$this->request->param('classes_id');
        }
        if ($classes_id > 0) {
            $r = model("Classplant")->where("id", "in", $classes_id)->select();
            if (isset($r)) {
                $classesname = preg_replace("/\(.*$/", "", $_REQUEST['classesName']);
                $classes = model("Classes")->where("name", "=", $classesname)->where("status", 1)->find();
                if (!isset($classes)) {
                    $this->error("班级不存在");
                }

                $r2 = model("Classroomeplan")->where("classes_id", "in", $classes["id"])->where("status", 1)->select();
                if (!isset($r2)) {
                    header("Location: /coursetable/classroomeplan/add?classesName=" . urlencode($_REQUEST['classesName']));
                    exit;
                }
                if (empty($r2)) {
                    header("Location: /coursetable/classroomeplan/add?classesName=" . urlencode($_REQUEST['classesName']));
                    exit;
                } else {
                    $ids = $r2[0]["id"];
                }
            } else {
                header("Location: /coursetable/classroomeplan/add?classesName=" . urlencode($_REQUEST['classesName']));
                exit;
            }
        }


        // 获取记录信息（可能是单个记录或多个记录）
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));

        // 获取该班级在该教学点的所有记录
        $allRecords = $this->model
            ->where("classes_id", $row['classes_id'])
            ->where("ocation_id", $row['ocation_id'])
            ->where("status", "<>", -1)
            ->select();

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $schedules = $this->request->post("schedules/a");

            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }

                    // 处理多时间段数据 - 每个时间段单独存储
                    $timeSchedules = [];
                    if (isset($schedules) && is_array($schedules)) {
                        // 验证时间段数据并准备单独的记录
                        foreach ($schedules as $schedule) {
                            if (
                                !isset($schedule['week']) || !isset($schedule['daytime']) ||
                                trim($schedule['week']) == "" || trim($schedule['daytime']) == ""
                            ) {
                                $this->error("请完整填写所有时间段");
                            }

                            $timeSchedules[] = [
                                'week' => trim($schedule['week']),
                                'daytime' => trim($schedule['daytime'])
                            ];
                        }
                    } else {
                        // 兼容原有的单时间段处理
                        if (!isset($params['daytime']) || trim($params['daytime']) == "") {
                            $this->error("请选择时段");
                        }

                        $timeSchedules[] = [
                            'week' => $params['week'],
                            'daytime' => $params['daytime']
                        ];
                    }

                    if (empty($timeSchedules)) {
                        $this->error("请至少添加一个时间段");
                    }

                    //验证是否使用对了教室的类型
                    $r = model("Ocation")->where("id", "in", $params["ocation_id"])->select();
                    $r2 = model("Classplant")->where("classes_id", "in", $params["classes_id"])->where("status", 1)->select();
                    if (isset($r)) {
                        $ocation_type = $r[0]["ocation_type"];
                        if (!in_array($ocation_type, explode(",", $r2[0]["ocation_type"]))) {
                            $this->error("该教室类型与所选教室类型不一致");
                        }
                    }

                    // 检查每个时间段的冲突（排除该班级在该教学点的所有现有记录）
                    $existingRecords = $this->model
                        ->where("classes_id", $params["classes_id"])
                        ->where("ocation_id", $params["ocation_id"])
                        ->where("status", "<>", -1)
                        ->select();

                    $excludeIds = [];
                    foreach ($existingRecords as $record) {
                        $excludeIds[] = $record['id'];
                    }

                    foreach ($timeSchedules as $schedule) {
                        $week = $schedule['week'];
                        $daytime = $schedule['daytime'];

                        // 检查该教室在该时间段是否已被其他记录占用
                        $conflictCheck = $this->checkTimeConflictWithExcludes($params["ocation_id"], $week, $daytime, $excludeIds);

                        if (!empty($conflictCheck)) {
                            $weekMap = ['1' => '周一', '2' => '周二', '3' => '周三', '4' => '周四', '5' => '周五', '6' => '周六', '7' => '周日'];
                            $weekText = isset($weekMap[$week]) ? $weekMap[$week] : $week;

                            // 获取冲突的班级和课程信息
                            $conflictClass = model("Classes")->where("id", "=", $conflictCheck[0]['classes_id'])->find();
                            $conflictClassName = $conflictClass ? $conflictClass['name'] : '未知班级';

                            $conflictCourse = model("Coursetable")->where("id", "=", $conflictCheck[0]['table_id'])->find();
                            $conflictCourseName = $conflictCourse ? $conflictCourse['name'] : '未知课程';

                            $this->error("教室在{$weekText} {$daytime}时段已被【{$conflictClassName}】的【{$conflictCourseName}】课程占用，请选择其他时间段或教室");
                        }
                    }

                    // 开始事务
                    $this->model->startTrans();

                    try {
                        // 删除该班级在该教学点的所有现有记录
                        $this->model
                            ->where("classes_id", $params["classes_id"])
                            ->where("ocation_id", $params["ocation_id"])
                            ->delete();

                        // 创建新的记录
                        $datatime = date("Y-m-d H:i:s");
                        $successCount = 0;

                        foreach ($timeSchedules as $schedule) {
                            $recordData = $params;
                            $recordData['week'] = $schedule['week'];
                            $recordData['daytime'] = $schedule['daytime'];
                            $recordData['create_time'] = $datatime;
                            $recordData['update_time'] = $datatime;
                            $recordData['status'] = 1;
                            unset($recordData['delete_time']);
                            unset($recordData['id']);

                            $result = $this->model->insertUpdate($recordData, ["table_id", "classes_id", "week", "daytime"]);
                            if ($result) {
                                $successCount++;
                            }
                        }

                        if ($successCount > 0) {
                            $this->model->commit();
                            $this->success("成功更新了 {$successCount} 条时间段记录");
                        } else {
                            $this->model->rollback();
                            $this->error("更新记录失败");
                        }
                    } catch (\Exception $e) {
                        $this->model->rollback();
                        throw $e;
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']);

        // 如果有多条记录，传递所有记录；否则传递单条记录
        if (count($allRecords) > 1) {
            $this->view->assign("row", json_encode($allRecords));
            $this->view->assign("isMultiRecord", true);
            // 为表单字段提供第一条记录的数据作为默认值
            $this->view->assign("formDefaults", $allRecords[0]);
        } else {
            $this->view->assign("row", $row);
            $this->view->assign("isMultiRecord", false);
            // 为表单字段提供当前记录的数据作为默认值
            $this->view->assign("formDefaults", $row);
        }

        return $this->view->fetch();
    }

    /**
     * 获取指定记录的所有时间安排
     */
    public function getSchedulesByRecord()
    {
        if ($this->request->isPost()) {
            $recordId = $this->request->post('record_id');

            if (!$recordId) {
                $this->error('记录ID不能为空');
            }

            try {
                // 获取指定记录
                $record = $this->model->get($recordId);
                if (!$record) {
                    $this->error('记录不存在');
                }

                // 获取该班级在该教学点的所有时间安排
                $schedules = $this->model
                    ->where("classes_id", $record['classes_id'])
                    ->where("ocation_id", $record['ocation_id'])
                    ->where("status", "<>", -1)
                    ->select();

                if ($schedules) {
                    $this->success('获取成功', '', $schedules);
                } else {
                    $this->success('获取成功', '', []);
                }
            } catch (\Exception $e) {
                $this->error('获取失败：' . $e->getMessage());
            }
        }

        $this->error('请求方式错误');
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $page = 1;
        $pagesize = 50;

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
            }
        }

        // 使用模型查询
        $query = $this->model->field('id,week as name');

        // 添加权限条件
        if ($_SESSION['think']['admin']['group_id'] != 1) {
            $query = $query->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
        }

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $query = $query->where($keyField, "=", $nn[$i]);
                    }
                }
            } else {
                $query = $query->where("status", "=", 1);
                if (isset($_REQUEST['city_id']) && $_REQUEST['city_id'] > 0) {
                    $query = $query->where("city_id", "=", $_REQUEST['city_id']);
                }
            }
        }

        $list = $query->limit(($page - 1) * $pagesize, $pagesize)->select();
        $list = collection($list)->toArray();

        //        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
        //        if (empty($list)&&!empty($r_name)) {
        //            $data = array(
        //                "type" => "file",
        //                "pid" => 0,
        //                "name" => $r_name[0]['name']."学科",
        //                "title" => $r_name[0]['name'],
        //                "ismenu" => 0,
        //                "createtime" => time(),
        //                "updatetime" => time(),
        //                "status" => 1,
        //                "school_id" => $_REQUEST['school_id'],
        //            );
        //            $this->model->create($data);
        //        }
        //        $sql="select id,pid,name,title,status from dev002_gxyusheng.fa_course_classroomeplan $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        //        $list = db()->query($sql);
        //        $tree = Tree::instance();
        //        $tree->init($list, 'pid');
        //        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        // 计算总数（使用相同的查询条件）
        $totalQuery = clone $query;
        $total = $totalQuery->count();
        echo json_encode(array("list" => $list, "total" => $total));
        exit;
    }

    // 导出方法
    public function export()
    {
        $where = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->select();
        $filename = 'classplant_export_' . date('YmdHis');

        $headers = [
            'ID',
            'Name',
            'Create Time' // 根据实际字段修改
        ];

        $data = [];
        foreach ($list as $item) {
            $data[] = [
                $item['id'],
                $item['name'],
                $item['create_time'],
            ];
        }
        $this->exportExcel($filename, $headers, $data);
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    /**
     * 检查班级是否有指定教室记录
     */
    public function checkRecord()
    {
        header('Content-Type: application/json');
        
        if ($this->request->isGet()) {
            $classesId = $this->request->get('classes_id');
            
            if (!$classesId) {
                echo json_encode([
                    'code' => 0,
                    'msg' => '班级ID不能为空',
                    'data' => null
                ]);
                exit;
            }
            
            try {
                // 查询该班级是否有指定教室记录
                $record = $this->model
                    ->where('classes_id', $classesId)
                    ->where('status', '<>', -1)
                    ->find();
                
                if ($record) {
                    // 有记录
                    echo json_encode([
                        'code' => 1,
                        'msg' => '查询成功',
                        'data' => [
                            'hasRecord' => true,
                            'record_id' => $record['id'],
                            'classes_id' => $record['classes_id'],
                            'ocation_id' => $record['ocation_id'],
                            'table_id' => $record['table_id']
                        ]
                    ]);
                } else {
                    // 没有记录
                    echo json_encode([
                        'code' => 1,
                        'msg' => '查询成功',
                        'data' => [
                            'hasRecord' => false
                        ]
                    ]);
                }
                exit;
            } catch (\Exception $e) {
                echo json_encode([
                    'code' => 0,
                    'msg' => '查询失败：' . $e->getMessage(),
                    'data' => null
                ]);
                exit;
            }
        }
        
        echo json_encode([
            'code' => 0,
            'msg' => '请求方式错误',
            'data' => null
        ]);
        exit;
    }

    /**
     * 获取时段占用详情（用于时段选择器显示）
     */
    public function getTimeSlotOccupancy()
    {
        header('Content-Type: application/json');

        if ($this->request->isPost()) {
            $ocationId = $this->request->post('ocation_id');
            $week = $this->request->post('week');
            $daytime = $this->request->post('daytime');
            $currentId = $this->request->post('current_id', 0);

            if (!$ocationId || !$week || !$daytime) {
                echo json_encode([
                    'code' => 0,
                    'msg' => '参数不完整',
                    'data' => null
                ]);
                exit;
            }

            try {
                // 构建查询对象
                $query = $this->model
                    ->alias('cp')
                    ->join('fa_course_table ct', 'cp.table_id = ct.id', 'LEFT')
                    ->join('eb_classes c', 'cp.classes_id = c.id', 'LEFT')
                    ->join('subject_lv s', 's.id = c.subject_lv', 'LEFT')
                    ->join([
                        '(SELECT ap1.classes_id, ap1.date, ap1.date as autoplan_end_date FROM fa_course_table_autoplan ap1 INNER JOIN (SELECT classes_id, MAX(date) as max_date FROM fa_course_table_autoplan GROUP BY classes_id) ap2 ON ap1.classes_id = ap2.classes_id AND ap1.date = ap2.max_date)' => 'ap'
                    ], 'ap.classes_id = c.id', 'LEFT')
                    ->where('cp.ocation_id', $ocationId)
                    ->where('cp.week', $week)
                    ->where('cp.daytime', $daytime)
                    ->where('cp.status', '<>', -1)
                    ->where('cp.id', '<>', $currentId) // 排除当前记录
                    ->field('cp.id, cp.table_id, cp.classes_id, s.name as course_name, c.name as class_name, ct.start_date, ct.end_date, ap.autoplan_end_date');

                // 打印SQL语句用于调试
//                $sql = $query->buildSql();
//                error_log("=== 时段占用查询SQL ===");
//                error_log("参数: ocationId={$ocationId}, week={$week}, daytime={$daytime}, currentId={$currentId}");
//                error_log("SQL: " . $sql);

                // 执行查询
                $occupiedRecord = $query->find();

                // 打印查询结果用于调试
                error_log("查询结果: " . json_encode($occupiedRecord));

                if ($occupiedRecord) {
                    // 计算释放时间
                    $releaseInfo = $this->calculateReleaseTime($occupiedRecord);

                    echo json_encode([
                        'code' => 1,
                        'msg' => '时段已被占用',
                        'data' => [
                            'occupied' => true,
                            'course_name' => isset($occupiedRecord['course_name']) ? $occupiedRecord['course_name'] : '未知课程',
                            'class_name' => isset($occupiedRecord['class_name']) ? $occupiedRecord['class_name'] : '未知班级',
                            'record_id' => isset($occupiedRecord['id']) ? $occupiedRecord['id'] : 0,
                            'release_info' => $releaseInfo
                        ]
                    ]);
                } else {
                    echo json_encode([
                        'code' => 1,
                        'msg' => '时段可用',
                        'data' => [
                            'occupied' => false
                        ]
                    ]);
                }
                exit;
            } catch (\Exception $e) {
                echo json_encode([
                    'code' => 0,
                    'msg' => '查询失败：' . $e->getMessage(),
                    'data' => null
                ]);
                exit;
            }
        }

        echo json_encode([
            'code' => 0,
            'msg' => '请求方式错误',
            'data' => null
        ]);
        exit;
    }

    /**
     * 计算课程释放时间
     * @param array $occupiedRecord 占用记录
     * @return string 释放日期
     */
    private function calculateReleaseTime($occupiedRecord)
    {
        $releaseInfo = '';

        try {
            // 优先使用autoplan的结束日期，如果没有则使用课程表的结束日期
            $endDate = $occupiedRecord['autoplan_end_date'] ?: $occupiedRecord['end_date'];

            if ($endDate && $endDate != '0000-00-00' && $endDate != '') {
                // 格式化结束日期
                $endDateTime = strtotime($endDate);
                if ($endDateTime) {
                    $releaseInfo = date('Y-m-d', $endDateTime) . '结束';
                }
            } else {
                // 没有结束日期信息
                $releaseInfo = '长期占用';
            }
        } catch (\Exception $e) {
            $releaseInfo = '时间未知';
        }

        return $releaseInfo;
    }

    /**
     * 检查教室时间冲突（按照原版逻辑）
     */
    public function checkConflict()
    {
        if ($this->request->isPost()) {
            $ocationId = $this->request->post('ocation_id');
            $schedules = $this->request->post('schedules/a');
            $currentId = $this->request->post('current_id', 0);

            if (!$ocationId || !$schedules) {
                $this->success('无冲突', []);
            }

            $conflicts = [];
            $weekMap = ['1' => '周一', '2' => '周二', '3' => '周三', '4' => '周四', '5' => '周五', '6' => '周六', '7' => '周日'];

            foreach ($schedules as $schedule) {
                $week = $schedule['week'];
                $daytime = $schedule['daytime'];

                if ($week && $daytime) {
                    // 检查该教室在该时间段是否已被占用
                    $query = $this->model
                        ->where("ocation_id", "=", $ocationId)
                        ->where("status", "<>", -1);

                    // 如果是编辑模式，排除当前记录
                    if ($currentId > 0) {
                        $query = $query->where("id", "<>", $currentId);
                    }

                    $conflictCheck = $this->checkTimeConflict($ocationId, $week, $daytime, $currentId);

                    if (!empty($conflictCheck)) {
                        foreach ($conflictCheck as $conflict) {
                            // 获取冲突的班级和课程信息
                            $conflictClass = model("Classes")->where("id", "=", $conflict['classes_id'])->find();
                            $conflictClassName = $conflictClass ? $conflictClass['name'] : '未知班级';

                            // 获取课程信息
                            $conflictCourse = model("Coursetable")->where("id", "=", $conflict['table_id'])->find();
                            $conflictCourseName = $conflictCourse ? $conflictCourse['name'] : '未知课程';

                            $conflicts[] = [
                                'week' => $week,
                                'daytime' => $daytime,
                                'week_text' => isset($weekMap[$week]) ? $weekMap[$week] : $week,
                                'daytime_text' => $daytime,
                                'time_range' => $daytime,
                                'conflict_time_range' => $conflict['daytime'],
                                'class_name' => $conflictClassName,
                                'course_name' => $conflictCourseName,
                                'conflict_id' => $conflict['id']
                            ];
                        }
                    }
                }
            }

            if (!empty($conflicts)) {
                $this->error('存在冲突', $conflicts);
            } else {
                $this->success('无冲突', []);
            }
        }

        $this->error('请求方式错误');
    }

    /**
     * 检查时间冲突的辅助方法
     * @param int $ocationId 教学点ID
     * @param string $week 周几
     * @param string $daytime 时段
     * @param int $excludeId 排除的记录ID（编辑时使用）
     * @return array 冲突记录
     */
    private function checkTimeConflict($ocationId, $week, $daytime, $excludeId = 0)
    {
        // 获取该教学点的所有有效记录
        $query = $this->model
            ->where("ocation_id", $ocationId)
            ->where("status", "<>", -1);

        // 如果需要排除某个记录（编辑时）
        if ($excludeId > 0) {
            $query = $query->where("id", "<>", $excludeId);
        }

        $allRecords = $query->select();
        $conflicts = [];

        // 检查每条记录是否与当前时间段冲突
        foreach ($allRecords as $record) {
            $recordWeeks = explode(',', $record['week']);
            $recordDaytimes = explode(',', $record['daytime']);

            // 检查周几是否匹配
            $weekMatch = false;
            foreach ($recordWeeks as $recordWeek) {
                $recordWeek = trim($recordWeek);
                if ($recordWeek == $week) {
                    $weekMatch = true;
                    break;
                }
            }

            // 检查时段是否匹配
            $daytimeMatch = false;
            if ($weekMatch) {
                foreach ($recordDaytimes as $recordDaytime) {
                    $recordDaytime = trim($recordDaytime);
                    if ($recordDaytime == $daytime) {
                        $daytimeMatch = true;
                        break;
                    }
                }
            }

            // 如果周几和时段都匹配，则存在冲突
            if ($weekMatch && $daytimeMatch) {
                $conflicts[] = $record;
            }
        }

        return $conflicts;
    }

    /**
     * 检查时间冲突的辅助方法（支持排除多个ID）
     * @param int $ocationId 教学点ID
     * @param string $week 周几
     * @param string $daytime 时段
     * @param array $excludeIds 排除的记录ID数组
     * @return array 冲突记录
     */
    private function checkTimeConflictWithExcludes($ocationId, $week, $daytime, $excludeIds = [])
    {
        // 获取该教学点的所有有效记录
        $query = $this->model
            ->where("ocation_id", $ocationId)
            ->where("status", "<>", -1);

        // 如果需要排除多个记录
        if (!empty($excludeIds)) {
            foreach ($excludeIds as $excludeId) {
                $query = $query->where("id", "<>", intval($excludeId));
            }
        }

        $allRecords = $query->select();
        $conflicts = [];

        // 检查每条记录是否与当前时间段冲突
        foreach ($allRecords as $record) {
            $recordWeeks = explode(',', $record['week']);
            $recordDaytimes = explode(',', $record['daytime']);

            // 检查周几是否匹配
            $weekMatch = false;
            foreach ($recordWeeks as $recordWeek) {
                $recordWeek = trim($recordWeek);
                if ($recordWeek == $week) {
                    $weekMatch = true;
                    break;
                }
            }

            // 检查时段是否匹配
            $daytimeMatch = false;
            if ($weekMatch) {
                foreach ($recordDaytimes as $recordDaytime) {
                    $recordDaytime = trim($recordDaytime);
                    if ($recordDaytime == $daytime) {
                        $daytimeMatch = true;
                        break;
                    }
                }
            }

            // 如果周几和时段都匹配，则存在冲突
            if ($weekMatch && $daytimeMatch) {
                $conflicts[] = $record;
            }
        }

        return $conflicts;
    }
}
